/*
 * textures.h
 *
 *  Created on: Dec 17, 2011
 *      Author: smejkalv
 */

#ifndef TEXTURES_H_
#define TEXTURES_H_

#include "utils/bmploader.h"
#include "utils/pngloader.h"

/**
 * Create texture from BMP file and return descriptor.
 */
GLuint loadBmpTexture(const char *filename) {
  Image *image = loadBMP(filename);

	GLuint textureId;
	glGenTextures(1, &textureId);
	glBindTexture(GL_TEXTURE_2D, textureId);
	glTexImage2D(GL_TEXTURE_2D,
			0,
			GL_RGB,
			image->width, image->height,
			0,
			GL_RGB,
			GL_UNSIGNED_BYTE,
			image->pixels);

  delete image;

	return textureId;
}

/**
 * Create texture from PNG file and return id.
 */
GLuint loadPngTexture(char *filename) {
  // The following two lines enable semi transparent
  glEnable(GL_BLEND);
  glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  int width, height;
  bool hasAlpha;
  GLubyte *textureImage;
  GLuint textureId;

  bool success = loadPngImage(filename, width, height, hasAlpha, &textureImage);
  if (!success) {
      std::cout << "Unable to load png file" << std::endl;
      return 0;
  }
  std::cout << "Image loaded " << width << " " << height << " alpha " << hasAlpha << std::endl;

	glGenTextures(1, &textureId);
	glBindTexture(GL_TEXTURE_2D, textureId);
  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? 4 : 3, width,
          height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE,
          textureImage);

  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	return textureId;
}

#endif /* TEXTURES_H_ */
